#!/usr/bin/env python
# -*- Python -*-

import sys
import time
sys.path.append(".")

# Import RTM module
import OpenRTM_aist
import RTC

import socket
import httplib
from time import sleep

# Import Service implementation class
# <rtc-template block="service_impl">

# </rtc-template>

# Import Service stub modules
# <rtc-template block="global_idl">

# </rtc-template>


# This module's spesification
# <rtc-template block="module_spec">
proxy_spec = ["implementation_id", "Proxy", 
		 "type_name",         "Proxy", 
		 "description",       "RTC-Lite for Arduino", 
		 "version",           "1.0.0", 
		 "vendor",            "AIST", 
		 "category",          "Proxy", 
		 "activity_type",     "STATIC", 
		 "max_instance",      "1", 
		 "language",          "Python", 
		 "lang_type",         "SCRIPT",
		 ""]

# </rtc-template>

class Proxy(OpenRTM_aist.DataFlowComponentBase):
	def __init__(self, manager):
		OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)

		# DataPorts initialization
		# <rtc-template block="data_ports">
		self._d_Watt  =RTC.TimedShort(RTC.Time(0,0),0)
		self._d_Light =RTC.TimedShort(RTC.Time(0,0),0)
		self._d_Temp  =RTC.TimedShort(RTC.Time(0,0),0)

		self._WattOut  =OpenRTM_aist.OutPort("Watt", self._d_Watt, OpenRTM_aist.RingBuffer(8))
		self._LightOut =OpenRTM_aist.OutPort("Light", self._d_Light, OpenRTM_aist.RingBuffer(8))
		self._TempOut  =OpenRTM_aist.OutPort("Temp", self._d_Temp, OpenRTM_aist.RingBuffer(8))

		# Set OutPort buffer
		self.registerOutPort("Watt",self._WattOut)
		self.registerOutPort("Light",self._LightOut)
		self.registerOutPort("Temp",self._TempOut)

		self._remoteIP=""

		# </rtc-template>


		# DataPorts initialization
		# <rtc-template block="service_ports">

		# </rtc-template>


		# initialize of configuration-data.
		# <rtc-template block="configurations">

		# </rtc-template>

		 
	def onInitialize(self):
		# Bind variables and configuration variable
		# <rtc-template block="bind_config">


		# </rtc-template>
		return RTC.RTC_OK


	#def onFinalize(self):
	#	return RTC.RTC_OK

	#def onStartup(self, ec_id):
	#	return RTC.RTC_OK

	#def onShutdown(self, ec_id):
	#	return RTC.RTC_OK

	def onActivated(self, ec_id):
		
		print "onActivated"

		host =''
		port =80
		address ="255.255.255.255"
		recv_port =1300
		recv_timeout =5

		s =socket.socket( socket.AF_INET, socket.SOCK_DGRAM)
		s.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
		s.bind( ( host, port))
		
		r =socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		r.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		r.bind((host, recv_port))
		r.settimeout( recv_timeout)

		max =5
		count =0
		while count <5:
			print "try: ", count

			s.sendto( str(count), ( address, port))
			try:
				message, ip_and_port = r.recvfrom(8192)
				if len( message) >0:
					print "message:", message, "from", ip_and_port
					self._remoteIP =ip_and_port[0]
					s.close()
					r.close()
					return RTC.RTC_OK
			except:
				count +=1
			
		s.close()
		r.close()
		return RTC.RTC_ERROR

	def onDeactivated(self, ec_id):
		print "onDeactivated!"
		return RTC.RTC_OK

	def onExecute(self, ec_id):
		print "onExecute!"
		
		conn =httplib.HTTPConnection( self._remoteIP)
		conn.request( "GET", "/EXE")
		r =conn.getresponse()				
		conn.close()

		print r.status, r.reason
		
		data =r.read()
		token =data.split( '\r\n')
		
		self._d_Watt.data  =int(token[0])
		self._d_Light.data =int(token[1])
		self._d_Temp.data  =int(token[2])

		print self._d_Watt.data
		print self._d_Light.data
		print self._d_Temp.data
		
		self._WattOut.write()
		self._LightOut.write()
		self._TempOut.write()

		time.sleep( 1)

		return RTC.RTC_OK

	#def onAborting(self, ec_id):
	#	return RTC.RTC_OK

	def onError(self, ec_id):
		print "onError!"
		return RTC.RTC_OK

	#def onReset(self, ec_id):
	#	return RTC.RTC_OK

	#def onStateUpdate(self, ec_id):
	#	return RTC.RTC_OK

	#def onRateChanged(self, ec_id):
	#	return RTC.RTC_OK




def MyModuleInit(manager):
    profile = OpenRTM_aist.Properties(defaults_str=proxy_spec)
    manager.registerFactory(profile,
                            Proxy,
                            OpenRTM_aist.Delete)

    # Create a component
    comp = manager.createComponent("Proxy")



def main():
	mgr = OpenRTM_aist.Manager.init(len(sys.argv), sys.argv)
	mgr.setModuleInitProc(MyModuleInit)
	mgr.activateManager()
	mgr.runManager()

if __name__ == "__main__":
	main()


